package com.slz3.business.module.orderManagement.ordOrder.steward;

import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.steward.Steward;
import com.slz3.business.frame.util.RedisClient;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.memberManagement.memMember.domain.MemMember;
import com.slz3.business.module.orderManagement.ordOrder.domain.OrdOrder;
import com.slz3.business.module.orderManagement.ordOrder.domain.OrdOrderFactory;
import com.slz3.business.module.orderManagement.ordOrder.domain.Order;
import com.slz3.business.module.orderManagement.ordOrderLine.domain.OrdOrderLine;
import com.slz3.business.module.orderManagement.ordOrderLine.domain.OrdOrderLineFactory;
import com.slz3.business.module.orderManagement.ordOrderLine.domain.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @FileName: OrdOrderSynr
 * @Description:订单增删改查同步工具类
 */

@Component
@Slf4j
public class OrdOrderSynr {

    /**
     * 下订单同步处理方法
     */
    public static void ordOrderAdd() {
        String orderUuid;
        try {
            orderUuid = Optional.ofNullable(Jedis.db0.leftPop(String.format("%s:%s", RK.ORDER, RK.SAVE_ORDER)).toString()).orElse("");
            //消费逻辑
            log.info("消费消息:" + orderUuid);
            if (VE.isNotEmpty(orderUuid)) {
                //根据map先获取订单信息并保存订单
                saveOrderUtilMethod(orderUuid);
                //处理完删除set集合
                RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.SAVE_ORDER.concat("Set")));

            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(String.format("%s:%s", RK.ORDER, RK.SAVE_ORDER.concat("Set")));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");
                if (VE.isNotEmpty(orderUuid)) {
                    //根据map先获取订单信息并保存订单
                    saveOrderUtilMethod(orderUuid);
                }
            }

            //删除set
            RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.SAVE_ORDER.concat("Set")));
        }
    }

    private static void saveOrderUtilMethod(String orderUuid) {
        Map<String, Object> orderInfoMap = Jedis.db0.getMap(RK.SERVICE__ORDER__INFO__ORDER_UUID__$UUID$.replace("${uuid}", orderUuid));
        Order order = Order.builder().build();
        Steward.map2Obj(orderInfoMap, order);
        OrdOrder ordOrder = OrdOrderFactory.newByOrder(order);

        OrdOrder newOrdOrder = Services.ordOrder.save(ordOrder);


        //获取订单详情信息并保存
        List<Object> orderDetailListUuid = Jedis.db0.getSet(RK.SERVICE__ORDER__JOIN__ORDER_DETAIL__ORDER_UUID__$UUID$.replace("${uuid}", orderUuid)).stream().collect(Collectors.toList());

        List<Object> orderDetailListObj = Jedis.db0.getListByKey(
                orderDetailListUuid.stream().map(item ->
                        RK.SERVICE__ORDER_DETAIL__INFO__ORDER_DETAIL_UUID__$UUID$
                                .replace("${uuid}", item.toString())).collect(Collectors.toList())
        );

        List<OrderDetail> orderDetailList = orderDetailListObj.stream().filter(item -> item != null).map(item -> {
            Map<String, Object> orderDetailMap = (Map) item;
            OrderDetail orderDetail = OrderDetail.builder().build();

            Steward.map2Obj(orderDetailMap, orderDetail);
            return orderDetail;
        }).collect(Collectors.toList());

        log.info(orderDetailList.toString());

        for (OrderDetail orderDetail : orderDetailList) {

            OrdOrderLine ordOrderLine = OrdOrderLineFactory.newByOrderDetail(orderDetail);
            ordOrderLine.setSerUserId(newOrdOrder.getSerUserId());
            ordOrderLine.setSerOrderAddressId(newOrdOrder.getSerOrderAddressId());
            Services.ordOrderLine.save(ordOrderLine);
        }
    }

    /**
     * 删除订单同步处理方法
     */
    public static void ordOrderDelete() {
        String orderUuid;
        try {
            orderUuid = (String) Jedis.db0.leftPop(String.format("%s:%s", RK.ORDER, RK.ORDER_DELETE));
            if (VE.isNotEmpty(orderUuid)) {
                Services.ordOrder.delete(Services.ordOrder.findAllByUuids(Arrays.asList(UUID.fromString(orderUuid))));
                //删除set
                RedisClient.redisTemplate.opsForSet().pop(RK.ORDER_DELETE.concat("Set"));
            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(String.format("%s:%s", RK.ORDER, RK.ORDER_DELETE.concat("Set")));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");

                if (VE.isNotEmpty(orderUuid)) {
                    Services.ordOrder.delete(Services.ordOrder.findAllByUuids(Arrays.asList(UUID.fromString(orderUuid))));
                }
            }

            //删除set
            RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.ORDER_DELETE.concat("Set")));
        }
    }

    /**
     * 取消订单同步处理方法
     */
    public static void ordOrderClose() {
        String orderUuid;
        try {
            orderUuid = Optional.ofNullable(Jedis.db0.leftPop(String.format("%s:%s", RK.ORDER, RK.CLOSE_ORDER)).toString()).orElse("");
            if (VE.isNotEmpty(orderUuid)) {
                updateOrder(orderUuid);
                //删除set
                RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.ORDER_DELETE.concat("Set")));
            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(String.format("%s:%s", RK.ORDER, RK.ORDER_DELETE.concat("Set")));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");
                if (VE.isNotEmpty(orderUuid)) {
                    updateOrder(orderUuid);
                }
            }
            //删除set
            RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.ORDER_DELETE.concat("Set")));
        }
    }

    /**
     * 取消订单同步处理方法
     */
    public static void confirmReceiver() {
        String orderUuid;
        try {
            orderUuid = Optional.ofNullable(Jedis.db0.leftPop(String.format("%s:%s:%s",RK.Sync, RK.ORDER, RK.CONFIRM_RECEIVER)).toString()).orElse("");
            if (VE.isNotEmpty(orderUuid)) {
                updateOrder(orderUuid);
                //删除set
                RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s:%s",RK.Sync, RK.ORDER, RK.CONFIRM_RECEIVER.concat("Set")));
            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(String.format("%s:%s:%s",RK.Sync, RK.ORDER, RK.CONFIRM_RECEIVER.concat("Set")));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");
                if (VE.isNotEmpty(orderUuid)) {
                    updateOrder(orderUuid);
                }
            }
            //删除set
            RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s:%s",RK.Sync, RK.ORDER, RK.CONFIRM_RECEIVER.concat("Set")));
        }
    }

    /**
     * 积分支付同步处理方法
     */
    public static void ordOrderJifenPay() {
        String orderUuid;
        try {
            orderUuid = (String) Jedis.db0.leftPop(String.format("%s:%s", RK.ORDER, RK.JIFEN_PAY));
            //减积分
            if (VE.isNotEmpty(orderUuid)) {
                updateOrder(orderUuid);
                //扣积分
                reduceJifen(orderUuid);
                //删除set
                RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.JIFEN_PAY.concat("Set")));
            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(String.format("%s:%s", RK.ORDER, RK.JIFEN_PAY.concat("Set")));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");
                if (VE.isNotEmpty(orderUuid)) {
                    updateOrder(orderUuid);
                    //扣积分
                    reduceJifen(orderUuid);
                }
            }

            //删除set
            RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.JIFEN_PAY.concat("Set")));
        }
    }

    /**
     * 支付宝支付同步处理方法
     */
    public static void ordOrderAliPay() {
        String orderUuid;
        try {
            orderUuid = (String) Jedis.db0.leftPop(String.format("%s:%s", RK.ORDER, RK.APPPAY_ALIPAYUPDATE));
            if (VE.isNotEmpty(orderUuid)) {
                updateOrder(orderUuid);
                //删除set
                RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.APPPAY_ALIPAYUPDATE.concat("Set")));
            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(String.format("%s:%s", RK.ORDER, RK.APPPAY_ALIPAYUPDATE.concat("Set")));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");
                if (VE.isNotEmpty(orderUuid)) {
                    updateOrder(orderUuid);
                }
            }

            //删除set
            RedisClient.redisTemplate.opsForSet().pop(String.format("%s:%s", RK.ORDER, RK.APPPAY_ALIPAYUPDATE.concat("Set")));
        }
    }

//    private static void updateOrderForAliPay(Map<String,Object> map){
//        //根据订单号获取订单id
//        String orderId = Jedis.db0.get(String.format("%s:%s",RK.APPPAY_GETALIPAYTRADEURL,map.get("out_trade_no")));
//        //根据orderId查询出订单
//        Optional<OrdOrder> oldOrder = Services.ordOrder.single(UUID.fromString(orderId));
//        OrdOrder ordOrder = oldOrder.get();
//        ordOrder.setSerPayType(PayTypeEnum.MONEY);
//        ordOrder.setSerPaymentTime(LocalDT.parseStringToDateTime(map.get("serPaymentTime").toString(),"yyyy-MM-dd HH:mm:ss"));
//        ordOrder.setSerPaymentType(PaymentTypeEnum.ALYAPY);
//        ordOrder.setSerPayNo(map.get("serPayNo").toString());
//        ordOrder.setSerOrderStatus(Integer.valueOf(map.get("serOrderStatus").toString()));
//        Services.ordOrder.modify(ordOrder);
//    }

    /**
     * 微信支付同步处理方法
     */
    public static void ordOrderWeixinPay() {
        String orderUuid;
        try {
            orderUuid = (String) Jedis.db0.leftPop(String.format("%s:%s", RK.ORDER, RK.APPPAY_WEIXINPAYUPDATE));
            if (VE.isNotEmpty(orderUuid)) {
                updateOrder(orderUuid);
                //删除set
                RedisClient.redisTemplate.opsForSet().pop(RK.APPPAY_WEIXINPAYUPDATE.concat("Set"));
            }
        } catch (Exception e) {
            //主数据set 集合
            Set members = Jedis.db0.getSet(RK.APPPAY_WEIXINPAYUPDATE.concat("Set"));
            System.out.println(members);
            Iterator iterator = members.iterator();
            //消费逻辑
            log.info("消费消息:" + members.toString());
            //根据map先获取订单信息并保存订单
            //遍历set集合
            while (iterator.hasNext()) {
                orderUuid = Optional.ofNullable(iterator.next().toString()).orElse("");
                if (VE.isNotEmpty(orderUuid)) {
                    updateOrder(orderUuid);
                }
            }
            //删除set
            RedisClient.redisTemplate.opsForSet().pop(RK.APPPAY_WEIXINPAYUPDATE.concat("Set"));
        }
    }

//    private static void updateOrderForWeiXin(Map<String,Object> map){
//        //根据订单号获取订单id
//        String orderId = Jedis.db0.get(String.format("%s:%s",RK.APPPAY_GETWEIXINPAYFORAOP,map.get("out_trade_no")));
//        //根据orderId查询出订单
//        Optional<OrdOrder> oldOrder = Services.ordOrder.single(UUID.fromString(orderId));
//        OrdOrder ordOrder = oldOrder.get();
//        ordOrder.setSerPayType(PayTypeEnum.MONEY);
//        ordOrder.setSerPaymentTime(LocalDT.parseStringToDateTime(map.get("serPaymentTime").toString(),"yyyyMMddHHmmss"));
//        ordOrder.setSerPaymentType(PaymentTypeEnum.WEIXIN);
//        ordOrder.setSerOrderNo(map.get("serPayNo").toString());
//        ordOrder.setSerOrderStatus(Integer.valueOf(map.get("serOrderStatus").toString()));
//        Services.ordOrder.modify(ordOrder);
//    }

    private static void updateOrder(String orderUuid) {
        Map<String, Object> orderInfoMap = Jedis.db0.getMap(RK.SERVICE__ORDER__INFO__ORDER_UUID__$UUID$.replace("${uuid}", orderUuid));

        Order order = Order.builder().build();

        Steward.map2Obj(orderInfoMap, order);

        OrdOrder ordOrder = OrdOrderFactory.newByOrder(order);

        Services.ordOrder.modify(ordOrder);
    }

    public static void reduceJifen(String orderUuid){
        OrdOrder ordOrder = Services.ordOrder.single(UUID.fromString(orderUuid)).get();

        MemMember memMember = Services.memMember.single(ordOrder.getSerUserId()).get();

        memMember.setSerScore(BigDecimal.valueOf(memMember.getSerScore()).subtract(ordOrder.getSerTotalFee()).intValue());

        Services.memMember.modify(memMember);
    }

}